<template>
  <div class="flight-change-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>航班变更管理</span>
          <el-button type="primary"
            @click="showAddDialog"
            v-if="isSuperAdmin"
          >
            新增变更
          </el-button>
        </div>
      </template>

      <el-table :data="filteredChanges" border style="width: 100%">
        <el-table-column prop="flightNumber" label="航班号" min-width="120" />
        <el-table-column prop="originalTime" label="原定时间" min-width="180" />
        <el-table-column prop="newTime" label="变更时间" min-width="180" />
        <el-table-column prop="changeType" label="变更类型" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getChangeTypeTag(row.changeType)">
              {{ row.changeType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="120" />
        <el-table-column label="操作" width="180" v-if="isSuperAdmin">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small" type="primary" @click="handleApprove(row)"
              v-if="row.status === '待审核'"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 变更表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        :model="changeForm" :rules="rules"
        ref="changeFormRef"
        label-width="120px"
      >
        <el-form-item label="航班号" prop="flightNumber">
          <el-input v-model="changeForm.flightNumber" />
        </el-form-item>

        <el-form-item label="变更类型" prop="changeType">
          <el-select v-model="changeForm.changeType" style="width: 100%">
            <el-option label="时间变更" value="时间变更" />
            <el-option label="航线变更" value="航线变更" />
            <el-option label="机型变更" value="机型变更" />
            <el-option label="取消航班" value="取消航班" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原定时间" prop="originalTime">
              <el-date-picker
                v-model="changeForm.originalTime"
                type="datetime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变更时间" prop="newTime">
              <el-date-picker
                v-model="changeForm.newTime"
                type="datetime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="变更原因" prop="reason">
          <el-input
            v-model="changeForm.reason"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

const store = useStore()

// 响应式数据
const changeForm = ref({
  id: '',
  flightNumber: '',
  changeType: '时间变更',
  originalTime: '',
  newTime: '',
  reason: '',
  status: '待审核',
  applicant: store.state.user?.username || ''
})

const changeList = ref([
  {
    id: '1',
    flightNumber: 'CA1234',
    changeType: '时间变更',
    originalTime: '2023-06-01 08:00',
    newTime: '2023-06-01 09:30',
    reason: '天气原因导致延误',
    status: '已批准',
    applicant: 'admin1'
  },
  {
    id: '2',
    flightNumber: 'MU5678',
    changeType: '航线变更',
    originalTime: '2023-06-01 14:00',
    newTime: '2023-06-01 15:00',
    reason: '目的地机场临时关闭',
    status: '待审核',
    applicant: 'admin2'
  }
])

const dialogVisible = ref(false)
const isAdd = ref(true)
const changeFormRef = ref(null)
const searchQuery = ref({
  flightNumber: '',
  status: ''
})

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 2
})

// 计算属性
const isSuperAdmin = computed(() => store.getters.isSuperAdmin)
const dialogTitle = computed(() => isAdd.value ? '新增航班变更' : '编辑航班变更')
const filteredChanges = computed(() => {
  return changeList.value.filter(item => {
    const matchesFlight = searchQuery.value.flightNumber === '' ||
      item.flightNumber.includes(searchQuery.value.flightNumber)
    const matchesStatus = searchQuery.value.status === '' ||
      item.status === searchQuery.value.status
    return matchesFlight && matchesStatus
  })
})

// 方法
const getChangeTypeTag = (type) => {
  const map = {
    时间变更: 'primary',
    航线变更: 'warning',
    机型变更: 'info',
    取消航班: 'danger'
  }
  return map[type] || ''
}

const getStatusTag = (status) => {
  const map = {
    待审核: 'warning',
    已批准: 'success',
    已拒绝: 'danger'
  }
  return map[status] || ''
}

const showAddDialog = () => {
  isAdd.value = true
  changeForm.value = {
    id: '',
    flightNumber: '',
    changeType: '时间变更',
    originalTime: '',
    newTime: '',
    reason: '',
    status: '待审核',
    applicant: store.state.user?.username || ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isAdd.value = false
  changeForm.value = { ...row }
  dialogVisible.value = true
}

const handleApprove = (row) => {
  row.status = '已批准'
  ElMessage.success('已批准该变更申请')
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
}

const submitForm = async () => {
  try {
    await changeFormRef.value.validate()
    if (isAdd.value) {
      changeForm.value.id = Date.now().toString()
      changeList.value.unshift({ ...changeForm.value })
      ElMessage.success('变更申请已提交')
    } else {
      const index = changeList.value.findIndex(item => item.id === changeForm.value.id)
      if (index !== -1) {
        changeList.value[index] = { ...changeForm.value }
        ElMessage.success('变更申请已更新')
      }
    }
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 表单验证规则
const rules = {
  flightNumber: [
    { required: true, message: '请输入航班号', trigger: 'blur' },
    { min: 5, max: 8, message: '航班号长度在5到8个字符', trigger: 'blur' }
  ],
  changeType: [
    { required: true, message: '请选择变更类型', trigger: 'change' }
  ],
  originalTime: [
    { required: true, message: '请选择原定时间', trigger: 'change' }
  ],
  newTime: [
    { required: true, message: '请选择变更时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (new Date(value) <= new Date(changeForm.value.originalTime)) {
          callback(new Error('变更时间必须晚于原定时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  reason: [
    { required: true, message: '请输入变更原因', trigger: 'blur' },
    { min: 10, message: '变更原因至少10个字符', trigger: 'blur' }
  ]
}
</script>

<style scoped>
.flight-change-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
